﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using System.Collections.ObjectModel;

namespace YourWorldServer
{
    public class PendingQuestsRepository
    {
        private static PendingQuestsRepository instance;
        private Dictionary<int, List<TeamEvent>> mapQuests;

        public event Action<TeamEvent> QuestCompletedEvent;

        private PendingQuestsRepository()
        {
            this.mapQuests = new Dictionary<int, List<TeamEvent>>();
        }

        public static PendingQuestsRepository Instance
        {
            get
            {
                if ( instance == null )
                    instance = new PendingQuestsRepository();

                return instance;
            }
        }

        public TeamEvent GetQuest( int mapId, int questId, int playerId )
        {
            if ( this.mapQuests.ContainsKey( mapId ) == false )
                return null;

            TeamEvent quest = this.mapQuests[mapId].Where( t => t.Quest.Id == questId ).FirstOrDefault();
            if ( quest == null )
                return null;

            if ( quest.Members.Where( p => p.Id == playerId ) != null )
                return quest;

            return null;
        }

        public void RemoveQuest( int mapId, int questId )
        {
            if ( this.mapQuests.ContainsKey( mapId ) == false )
                return;

            TeamEvent teamQuest = this.mapQuests[mapId].Where( x => x.Id == questId ).FirstOrDefault();
            this.mapQuests[mapId].Remove( teamQuest );
        }

        public void JoinQuest( Player player, Event quest )
        {
            if ( this.mapQuests.ContainsKey( player.MapId ) == false )
                this.mapQuests.Add( player.MapId, new List<TeamEvent>() );

            TeamEvent teamQuest = this.mapQuests[player.MapId].Where( x => x.Id == quest.Id ).FirstOrDefault();

            if ( teamQuest == null )
            {
                teamQuest = new TeamEvent()
                {
                    Quest = quest,
                    Members = new ObservableCollection<Player>(),
                    MembersCount = 0,
                    Id = quest.Id
                };

                teamQuest.Quest.PlayerId = player.Id;
                this.mapQuests[player.MapId].Add( teamQuest );
            }

            teamQuest.Members.Add( player );

            if ( teamQuest.Members.Count == teamQuest.Quest.RequiredMembersCount )
            {
                this.QuestCompletedEvent( teamQuest );
            }
        }
    }

}
